/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bionic.ce.commands.queries;

import com.bionic.ce.beans.Query;
import com.bionic.ce.beans.Systemacc;
import com.bionic.ce.businesslogic.QueryService;
import com.bionic.ce.businesslogic.SystemAccService;
import com.bionic.ce.commands.ICommand;
import com.bionic.ce.commands.systemacc.CommandGoToSystemAccountInfo;
import com.bionic.ce.manager.Config;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author MAXIM
 */
public class CommandUpdateMyQuery implements ICommand {

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String page = null;
        Integer queryId = null;
        Integer openByUser = null;
        Date openDate = null;
        Date finishDate = null;
        Double amount = null;
        String currencyFrom = null;
        String currencyTo = null;
        Double rateFrom = null;
        Double rateTo = null;
        try {
            queryId = Integer.parseInt(request.getParameter("queryId"));
            openByUser = Integer.parseInt(request.getParameter("openByUser"));
            openDate = new java.util.Date();
            amount = Double.parseDouble(request.getParameter("amount"));
            currencyFrom = request.getParameter("currencyFromShortName");
            currencyTo = request.getParameter("currencyToShortName");
            rateFrom = Double.parseDouble(request.getParameter("rateFrom"));
            rateTo = Double.parseDouble(request.getParameter("rateTo"));
            Query query = new Query();
            query.setQueryId(queryId);
            query.setOpenByUser(openByUser);
            query.setOpenDate(openDate);
            query.setAmount(amount);
            query.setCurrencyFrom(currencyFrom);
            query.setCurrencyTo(currencyTo);
            query.setRateFrom(rateFrom);
            query.setRateTo(rateTo);
            query.setStatus("Active");
            if (currencyFrom.equals(currencyTo)) {
                throw new IllegalArgumentException("Currency from and Currency to can`t be the same");
            }
            if (rateFrom > rateTo) {
                throw new IllegalArgumentException("Rate from couldn`t be more than Rate to");
            }

            Systemacc systemAcc = new Systemacc();
            systemAcc.setUserId(openByUser);
            systemAcc.setCurrency(currencyFrom);
            try {
                systemAcc = (Systemacc) (SystemAccService.returnCurrentSystemAccountsInfo(openByUser, currencyFrom).toArray())[0];
            } catch (ArrayIndexOutOfBoundsException ex) {
                throw new IllegalArgumentException("You can`t exchange money from "
                        + currencyFrom + " to " + currencyTo + " because you don`t have System account in " + currencyFrom);
            }
            if (amount > systemAcc.getAmount()) {
                throw new IllegalArgumentException("You don`t have enough money on yours System account in " + currencyFrom);
            }
            String s= request.getParameter("finishDate");
            String a[]=s.split("T");
            String s1=a[0]+" "+a[1];
            System.out.println(s1);
            finishDate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(s1);
//            finishDate = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("finishDate"));
            query.setFinishDate(finishDate);
            if (finishDate.before(openDate)) {
                throw new IllegalArgumentException("Wrong value of finish date");
            }

            QueryService.updateCurrentQuery(query);
            boolean b = false;
            Query searchQuery = new Query();
            searchQuery.setCurrencyFrom(currencyTo);
            searchQuery.setCurrencyTo(currencyFrom);
            searchQuery.setStatus("Active");
            List<Query> searchlist = QueryService.findByDynamicSelect(searchQuery);
            Double minAm = (double) ((int) Math.round((amount * rateFrom) * 1000)) / 1000;
            Double maxAm = (double) ((int) Math.round((amount * rateTo) * 1000)) / 1000;
            System.out.println(searchlist);
            if (!searchlist.isEmpty()) {
                for (Query searchQ : searchlist) {
                    Double searchminAm = (double) ((int) Math.round((searchQ.getAmount() * searchQ.getRateFrom()) * 1000)) / 1000;
                    Double searchmaxAm = (double) ((int) Math.round((searchQ.getAmount() * searchQ.getRateTo()) * 1000)) / 1000;
                    System.out.println(searchQ);
                    System.out.println("if ("+searchQ.getAmount()+" >=" +" "+ minAm+" & "+searchQ.getAmount()+" <="+ maxAm +" & "+ 
                            amount +" >= "+ searchminAm+" & "+ amount+" <= "+searchmaxAm);
                    if (searchQ.getAmount() >= minAm & searchQ.getAmount() <= maxAm
                            & amount >= searchminAm & amount <= searchmaxAm) {
                        System.out.println("query is good");
                        SystemAccService.executedQueryMoneyTransfer(openByUser, currencyFrom, currencyTo, searchQ.getOpenByUser(), amount, searchQ.getAmount());
                        query.setStatus("Executed By System");
                        Double closedRate = (double) ((int) Math.round((searchQ.getAmount() / amount) * 1000)) / 1000;
                        query.setClosedRate(closedRate);
                        query.setClosedDate(new Date());
                        query.setExecutedByUser(searchQ.getOpenByUser());
                        QueryService.updateCurrentQuery(query);

                        searchQ.setStatus("Executed By System");
                        closedRate = (double) ((int) Math.round((amount / searchQ.getAmount()) * 1000)) / 1000;
                        searchQ.setClosedRate(closedRate);
                        searchQ.setClosedDate(new Date());
                        searchQ.setExecutedByUser(openByUser);
                        QueryService.updateCurrentQuery(searchQ);

                        request.setAttribute("succesexchange", "Query was automatically exchanged. "
                                + "From yours system account were withdrawed " + String.format("%.2f", amount) + " " + currencyFrom + " "
                                + currencyTo + " and were deposited " + String.format("%.2f", searchQ.getAmount()) + ".");
                        new CommandGoToSystemAccountInfo().execute(request, response);
                        page = Config.getInstance().getProperty(Config.GOTOSYSTEMACCAOUNTSINFO);
                        b = true;
                        break;
                    }
                }
            }
            System.out.println(b);
            if (!b) {
                page = Config.getInstance().getProperty(Config.GOTOMYQUERIES);
            }
        } catch (ParseException ex) {
            request.setAttribute("myqueryupdateerror", "Wrong value of finish date. Please provide correct value.");
            page = Config.getInstance().getProperty(Config.GOTOMYQUERYUPDATE);
        } catch (NumberFormatException ex) {
            request.setAttribute("myqueryupdateerror", "Please enter correct values to such fields: Amount, Rate from and Rate to");
            page = Config.getInstance().getProperty(Config.GOTOMYQUERYUPDATE);
        } catch (IllegalArgumentException ex) {
            request.setAttribute("myqueryupdateerror", ex.getMessage());
            page = Config.getInstance().getProperty(Config.GOTOMYQUERYUPDATE);
        } catch (IllegalStateException ex) {
            request.setAttribute("myqueryupdateerror", "Not all required fields are filled");
            page = Config.getInstance().getProperty(Config.GOTOMYQUERYUPDATE);
        } finally {
            request.setAttribute("finishDate", finishDate);
            request.setAttribute("amount", amount);
            request.setAttribute("currencyFromShortName", currencyFrom);
            request.setAttribute("currencyToShortName", currencyTo);
            request.setAttribute("rateFrom", rateFrom);
            request.setAttribute("rateTo", rateTo);
        }
        (new CommandGoToMyQueries()).execute(request, response);
        return page;
    }
}
